<template>
  <div class="wrapper-add-edit">
    <el-form ref="refForm" :rules="rules" :model="formData" label-width="120px">
      <el-form-item label="所属类别">
        <el-radio-group v-model="tagId" @change="onTagChange">
          <el-radio v-for="item in allCategoryTagList" :key="item.id" :value="item.id" :label="item.label" />
        </el-radio-group>
      </el-form-item>

      <el-form-item label="选择上级分类" style="max-width: 600px">
        <el-tree-select
          v-model="formData.idParent"
          :data="treeSelectData"
          :props="{ value: 'id', label: 'label' }"
          :render-after-expand="false"
          :current-node-key="0"
          value-key="id"
          placeholder="选择上级分类"
          check-strictly
        />
      </el-form-item>

      <el-form-item label="分类名称" style="max-width: 600px" prop="label">
        <el-input ref="refTitle" v-model="formData.label" maxlength="16" show-word-limit />
      </el-form-item>

      <el-form-item label="排序值">
        <el-input-number v-model="formData.weight" :min="1" :max="99" controls-position="right" />
      </el-form-item>

      <el-form-item label="默认标题图">
        <TheUploaderImage @setUploadResult="getUploadResult($event)" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onAdd">确定添加</el-button>
        <el-button @click="onBack2List">取消并返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { AryToTree } from '@/utils/array'
import { toastError, toastSuccess } from '@/utils/toast'
import { getLStorage, getLStorageObj } from '@/utils/web-storage'

import TheUploaderImage from '@/components/UploadImage2Local'

import router from '@/router'
import store from '@/store'
import { defineComponent, ref, onMounted } from 'vue'
export default defineComponent({
  name: 'CategoryAddView',
  components: {
    TheUploaderImage,
  },
  setup() {
    const allCategoryTagList = ref([])
    const tagId = ref(1)
    const tagLabel = ref('')
    const allCategoryList = ref([])
    const treeSelectData = ref([])
    const formData = ref({
      id: 0,
      tag: '',
      idParent: 1,
      depth: 1,
      weight: 99,
      label: '',
      flagSystem: 0,
      urlCoverImg: '',
    })
    const refForm = ref(null)
    const rules = ref({
      label: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
    })

    const initAllCategoryTagList = () => {
      allCategoryTagList.value = JSON.parse(getLStorage('AllCategoryTag'))
      tagId.value = allCategoryTagList.value[0].id
      tagLabel.value = allCategoryTagList.value[0].label
    }

    const onTagChange = (e) => {
      listAllCategory(e)
      for (let i = 0; i < allCategoryTagList.value.length; i++) {
        if (e === allCategoryTagList.value[i].id) {
          formData.value.idParent = allCategoryTagList.value[i].id
          tagLabel.value = allCategoryTagList.value[i].label
        }
      }
    }
    const listAllCategory = (e) => {
      allCategoryList.value = getLStorageObj('AllCategory')
      treeSelectData.value = AryToTree(allCategoryList.value, parseInt(e))
    }
    // 设置封面图
    const getUploadResult = (val) => {
      formData.value.urlCoverImg = JSON.stringify(val)
    }
    const onAdd = () => {
      if (!tagLabel.value) {
        toastError('请选择所属类别！')
        return
      }
      formData.value.tag = tagLabel.value
      for (let i = 0; i < allCategoryList.value.length; i++) {
        if (formData.value.idParent === allCategoryList.value[i].id) {
          formData.value.depth = allCategoryList.value[i].depth + 1
          break
        }
      }
      refForm.value.validate((valid) => {
        if (!valid) {
          return false
        }
        store
          .dispatch('sys_category/add', formData.value)
          .then(() => {
            toastSuccess('添加分类成功！')
            onBack2List()
          })
          .catch((error) => {
            console.log('服务器添加分类时返回错误：', error)
          })
      })
    }
    const onBack2List = () => {
      router.push({ path: 'list-all' })
    }

    onMounted(() => {
      initAllCategoryTagList()
      listAllCategory(1)
    })

    return {
      allCategoryTagList,
      tagId,
      tagLabel,
      allCategoryList,
      treeSelectData,
      formData,
      rules,
      refForm,
      onTagChange,
      initAllCategoryTagList,
      listAllCategory,
      getUploadResult,
      onAdd,
      onBack2List,
    }
  },
})
</script>

<style lang="scss" scoped></style>
